import { reqGoodsInfo, reqAddOrUpdateShopCart } from "@/api";
// 封装游客身份的模块 uuid --> 生成一个随机字符串
import { getUUID } from '@/utils/uuid_token'

const actions = {
    async getGoodsInfo({ commit }, skuId) {
        let result = await reqGoodsInfo(skuId);
        if (result.code == 200) {
            commit('GETGOODSINFO', result.data);
        }
    },
    async addOrUpdateShopCart({ commit }, { skuId, skuNum }) {
        // 加购以后 页面没有做其他事情，到此结束
        let result = await reqAddOrUpdateShopCart(skuId, skuNum)
        if (result.code == 200) {
            return Promise.resolve()
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
};

const mutations = {
    GETGOODSINFO(state, goodsInfo) {
        state.goodsInfo = goodsInfo;
    },
};

const state = {
    goodsInfo: {},
    uuid_token: getUUID(),
};

// 简化数据
const getters = {
    categoryView(state) {
        // 因为state.goodsInfo的初始值为空对象，空对象.categoryView为undefined
        // 所以 return state.goodsInfo.categoryView 会报错
        return state.goodsInfo.categoryView || {}
    },
    skuInfo(state) {
        return state.goodsInfo.skuInfo || {}
    },
    spuSaleAttrList(state) {
        return state.goodsInfo.spuSaleAttrList || []
    },
};

export default {
    state, actions, mutations, getters
}